﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Threading;
using System.Threading.Tasks;

using SF.Collections.Concurrent;

namespace SF.WebClient.Controllers
{
    public abstract class BasicController : Controller
    {
        /// <summary>
        /// 源代码图片信息缓存，其字典格式如下：Key 表示“请求的地址（即/控制器/行为）”，Value 表示“图片相对路径”。
        /// </summary>
        public static ObservableConcurrentDictionary<string, string> SourceCodeJpgInfoCache = new ObservableConcurrentDictionary<string, string>();

        /// <summary>
        /// 是否正在截屏
        /// </summary>
        public static bool CaptureState { get; set; }

        /// <summary>
        /// 捕获屏幕
        /// </summary>
        protected void CaptureImage()
        {
            string url = Request.Url.OriginalString, urlWithoutParam = Request.Url.AbsolutePath;
            string controller = RouteData.Values["controller"] as string;
            try
            {
                string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
                string relativePath = "~/Temp/" + controller + "/", absolutePath = Server.MapPath(relativePath);
                if (!System.IO.Directory.Exists(absolutePath)) { System.IO.Directory.CreateDirectory(absolutePath); }
                string relativeFilePath = relativePath + fileName, absoluteFilePath = absolutePath + fileName;
                //SF.Utilities.DrawHelper.GetImage thumb = new SF.Utilities.DrawHelper.GetImage(url, Request.Browser);
                SF.Utilities.DrawHelper.GetImage thumb = new SF.Utilities.DrawHelper.GetImage(url, 1280, 1560, 1280, 1560);
                SourceCodeJpgInfoCache.Add(urlWithoutParam, relativeFilePath); CaptureState = true;
                System.Drawing.Bitmap x = thumb.GetBitmap();

                x.Save(absoluteFilePath);
            }
            catch (Exception ex)
            {
                CaptureState = false;
                SourceCodeJpgInfoCache.Remove(urlWithoutParam);
                SF.Utilities.Log4Helper.Info("捕获屏幕时发生异常：" + ex.Message);
            }
        }

        /// <summary>
        /// 保存原始页面为图片
        /// </summary>
        /// <returns>操作成功返回 true，否则返回 false。</returns>
        protected bool SaveOriginalPageToImage()
        {
            Thread NewTh = new Thread(CaptureImage);
            NewTh.SetApartmentState(ApartmentState.STA);
            NewTh.Start();
            while (NewTh.ThreadState == ThreadState.Running)
            {
            }

            return CaptureState;
        }

        /// <summary>
        /// 输出指定路径的js文件的源码信息
        /// </summary>
        /// <param name="relativePath">js文件的相对路径</param>
        protected void WriteSourceCode(string relativePath)
        {
            string content = Helper.FileHelper.ReadFile(relativePath);
            Response.Write("<pre>" + content + "</pre>");
        }
	}
}